package cn.edu.njust.heartbeat;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

import java.net.SocketAddress;
import java.util.LinkedList;
import java.util.List;

@Slf4j
public class HeartBeatServerHandler extends ChannelInboundHandlerAdapter {
    private static final List<SocketAddress> clients = new LinkedList<>();

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        clients.add(ctx.channel().remoteAddress());
        log.info("客户端{}连接", ctx.channel().remoteAddress());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        clients.remove(ctx.channel().remoteAddress());
        log.info("客户端{}断开连接", ctx.channel().remoteAddress());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        log.info("收到客户端{}的心跳消息", ctx.channel().remoteAddress());
        log.info("当前存活列表为{}", clients);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            log.info("客户端{}失去联系，关闭连接", ctx.channel().remoteAddress());
            clients.remove(ctx.channel().remoteAddress());
            ctx.close();
        }
    }
}
